package com.common.zxing;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.common.zxing.camera.CameraManager;
import com.common.zxing.common.BitmapUtils;
import com.common.zxing.decode.CaptureActivityHandler;
import com.common.zxing.decode.QRCodeDecoder;
import com.common.zxing.view.ScrollLayout;
import com.common.zxing.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public abstract class BaseCaptureOaActivity extends BaseActivity implements
        SurfaceHolder.Callback {

    private static final String TAG = BaseCaptureActivity.class.getSimpleName();
    protected static final int FORMAT_BITMAP_COMPLETE = 10001;
    protected static final int COMPRESS_BITMAP_COMPLETE = 10002;

    private static final int PARSE_BARCODE_FAIL = 300;
    private static final int PARSE_BARCODE_SUC = 200;

    private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
    private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;

    private static final String[] ZXING_URLS = {
            "http://zxing.appspot.com/scan", "zxing://scan/"};

    public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
    private static final int REQUEST_CODE_SCAN_GALLERY = 0x0000bacd;


    private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES = EnumSet
            .of(ResultMetadataType.ISSUE_NUMBER,
                    ResultMetadataType.SUGGESTED_PRICE,
                    ResultMetadataType.ERROR_CORRECTION_LEVEL,
                    ResultMetadataType.POSSIBLE_COUNTRY);

    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private Result savedResultToShow;
    private ViewfinderView viewfinderView;
    //    private TextView statusView;
//    private View resultView;
    private Result lastResult;
    private boolean hasSurface;
    private boolean copyToClipboard;
    private IntentSource source;
    private String sourceUrl;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private AmbientLightManager ambientLightManager;
    private ImageView iv_back;
    private ImageView mTakePhoto;
    private LinearLayout llMore;
    private View statusView;

    FrameLayout capture_frame;
    private boolean isfisrt = false;


    private SurfaceView mSurfaceView;
    private ScrollLayout mScrollLayout;
    private int mCurrentMode = ScrollLayout.INDEX_SECOND;

    public static BaseCaptureOaActivity _instance;

    @Override
    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }


    boolean isFlashOn;

    public boolean playSound = false;


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        _instance = this;
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_captureoa);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        ambientLightManager = new AmbientLightManager(this);
        capture_frame = (FrameLayout) findViewById(R.id.capture_frame);


        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        iv_back = (ImageView) findViewById(R.id.iv_back);

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getIntent().hasExtra("shortcut")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.setClassName("com.ch999.mobileoa", "com.ch999.mobileoa.page.PageActivity");
                    startActivity(intent);
                }
                finish();
            }
        });

        mTakePhoto = (ImageView) findViewById(R.id.take_photo);
        llMore = (LinearLayout) findViewById(R.id.llmore);

        mTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Camera camera = cameraManager.getCamera();
                Camera.Parameters cameraParameters = camera.getParameters();
                List<Camera.Size> supportedPictureSizes = cameraParameters.getSupportedPictureSizes();
                Camera.Size size = supportedPictureSizes.get(supportedPictureSizes.size() / 2);
                cameraParameters.setPictureSize(size.width, size.height);
                camera.setParameters(cameraParameters);
                camera.setDisplayOrientation(90);
                camera.takePicture(null, null, jpegCallback);
                showDialog();
            }
        });

        findViewById(R.id.ivPhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开手机中的相册

                Intent intent = new Intent(BaseCaptureOaActivity.this, MultiImageSelectorActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
                // 最大图片选择数量

                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, MultiImageSelectorActivity.MODE_MULTI);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                // 默认选择图片,回填选项(支持String ArrayList)
                intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, new ArrayList<String>());
                startActivityForResult(intent, REQUEST_CODE_SCAN_GALLERY);

            }
        });
        final ImageView ivFlash = (ImageView) findViewById(R.id.ivFlash);
        ivFlash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开或关闭闪光灯
                try {
                    boolean isSuccess = cameraManager.setFlashLight(!isFlashOn);
                    if (!isSuccess) {
                        Toast.makeText(BaseCaptureOaActivity.this, "暂时无法开启闪光灯", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (isFlashOn) {
                        // 关闭闪光灯
                        ivFlash.setImageResource(R.drawable.qrcode_scan_btn_flash_down);
                        isFlashOn = false;
                    } else {
                        // 开启闪光灯
                        ivFlash.setImageResource(R.drawable.qrcode_scan_btn_scan_off);
                        isFlashOn = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        });

        mScrollLayout = (ScrollLayout) findViewById(R.id.scroll_layout);
        mScrollLayout.setOnSelectChangedListener(new ScrollLayout.IOnSelectChanged() {
            @Override
            public void selectChanged(int index) {
                if (index == ScrollLayout.INDEX_SECOND && mCurrentMode != ScrollLayout.INDEX_SECOND) {
                    mTakePhoto.setVisibility(View.INVISIBLE);
                    llMore.setVisibility(View.VISIBLE);
//                    viewfinderView.setIsScanNumber(false);
//                    statusView.setText(R.string.msg_default_status);
//                    onResumeOperation();
                    viewfinderView.drawTextHint(getResources().getString(R.string.msg_default_status));
                    restartPreviewAfterDelay(0L);
                    mCurrentMode = ScrollLayout.INDEX_SECOND;
                } else if (index == ScrollLayout.INDEX_THIRD && mCurrentMode != ScrollLayout.INDEX_THIRD) {
                    mTakePhoto.setVisibility(View.VISIBLE);
                    llMore.setVisibility(View.GONE);
//                    viewfinderView.setIsScanNumber(true);
//                    statusView.setText(R.string.msg_number_status);
//                    onPauseOperation();
                    viewfinderView.drawTextHint(getResources().getString(R.string.msg_number_status));

                    restartPreviewAfterDelay(0L);

                    mCurrentMode = ScrollLayout.INDEX_THIRD;
                }
                switchScanMode(index);
            }
        });
    }

    String mFilePath;

    private void save(byte[] data) {
        mFilePath = this.getExternalCacheDir().getAbsolutePath() + System.currentTimeMillis() + ".jpg";
        File file = new File(mFilePath);
        try {
            if (!file.exists())
                //创建文件
                file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


        Luban.with(this).load(file).putGear(3).setCompressListener(new OnCompressListener() {
            public void onStart() {
            }

            public void onSuccess(File file) {
                mFilePath = file.getAbsolutePath();
                mHandler.obtainMessage(COMPRESS_BITMAP_COMPLETE).sendToTarget();
            }

            public void onError(Throwable e) {
            }
        }).launch();
    }

    public void setStatusViewHeight(int height) {
        statusView = findViewById(R.id.statusView);

        if (statusView != null) {
            statusView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height));
        }
    }

    protected void barcodeMode() {
        mTakePhoto.setVisibility(View.VISIBLE);
        llMore.setVisibility(View.GONE);
        mScrollLayout.setVisibility(View.GONE);

        viewfinderView.drawTextHint(getResources().getString(R.string.msg_number_status));

        restartPreviewAfterDelay(0L);
        mCurrentMode = ScrollLayout.INDEX_THIRD;
    }


    /**
     * 播放声音
     */
    @Override
    public void playSound() {
        if (playSound)
            beepManager.playBeepSoundAndVibrate();
    }

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case FORMAT_BITMAP_COMPLETE:
                    Bitmap bm = (Bitmap) msg.obj;
                    save(Bitmap2Bytes(bm));
                    break;
                case COMPRESS_BITMAP_COMPLETE:
                    BarcodeRecognition(mFilePath);
                    break;
                case PARSE_BARCODE_SUC: // 解析图片成功
//                    Result result = (Result) msg.obj;
//                    Toast.makeText(BaseCaptureOaActivity.this, "解析成功，结果为：" + result.getText(), Toast.LENGTH_SHORT).show();

                    playSound();
                    handleDecodeInternally((Result) msg.obj);
                    break;


                case PARSE_BARCODE_FAIL:// 解析图片失败

                    Toast.makeText(BaseCaptureOaActivity.this, "识别失败",
                            Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    private Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(final byte[] data, final Camera camera) {
            camera.startPreview();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bm0 = BitmapFactory.decodeByteArray(data, 0, data.length);
                    Matrix m = new Matrix();
                    m.setRotate(90, (float) bm0.getWidth(), (float) bm0.getHeight());
                    Bitmap tempMap = Bitmap.createBitmap(bm0, 0, 0, bm0.getWidth(), bm0.getHeight(), m, true);
                    final Bitmap bm = Bitmap.createBitmap(tempMap, tempMap.getWidth() / 6, tempMap.getHeight() / 3, tempMap.getWidth() * 2 / 3, tempMap.getHeight() / 3);
                    Camera.Parameters ps = camera.getParameters();
                    if (ps.getPictureFormat() == PixelFormat.JPEG) {
                        //存储拍照获得的图片
                        mHandler.obtainMessage(FORMAT_BITMAP_COMPLETE, bm).sendToTarget();
                    }
                }
            }).start();
        }
    };

    protected void showDialog() {

    }

    protected void BarcodeRecognition(String path) {

    }

    protected void switchScanMode(int index) {

    }

    private byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }


    @Override
    protected void onResume() {
        super.onResume();


        // 相机初始化的动作需要开启相机并测量屏幕大小，这些操作
        // 不建议放到onCreate中，因为如果在onCreate中加上首次启动展示帮助信息的代码的 话，
        // 会导致扫描窗口的尺寸计算有误的bug
        cameraManager = new CameraManager(getApplication(), 240, 240, 1200, 1200);

        viewfinderView = (ViewfinderView) findViewById(R.id.capture_viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);


        String customPromptMessage = getIntent()
                .getStringExtra(Intents.Scan.PROMPT_MESSAGE);
        if (customPromptMessage != null) {
            viewfinderView.drawTextHint(customPromptMessage);
        } else {
            viewfinderView.drawTextHint(mCurrentMode == ScrollLayout.INDEX_SECOND ? getResources().getString(R.string.msg_default_status) : getResources().getString(R.string.msg_number_status));

        }

        handler = null;
        lastResult = null;

        // 摄像头预览功能必须借助SurfaceView，因此也需要在一开始对其进行初始化
        // 如果需要了解SurfaceView的原理
        // 参考:http://blog.csdn.net/luoshengyang/article/details/8661317
//        surfaceView = findViewById(R.id.view_capture_preview);
//        surfaceView = new SurfaceView(this);
//        ((FrameLayout)findViewById(R.id.capture_frame)).addView(surfaceView,0);

        mSurfaceView = new SurfaceView(this);
//        if (capture_frame.getChildCount() > 3) {
//            capture_frame.removeViewAt(0);
//        }
        capture_frame.addView(mSurfaceView, 0);
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        if (hasSurface) {
            // The activity was paused but not stopped, so the surface still
            // exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(surfaceHolder);

        } else {
            // 防止sdk8的设备初始化预览异常
//            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

            // Install the callback and wait for surfaceCreated() to init the
            // camera.
            surfaceHolder.addCallback(this);
        }

        // 加载声音配置，其实在BeemManager的构造器中也会调用该方法，即在onCreate的时候会调用一次
        beepManager.updatePrefs();

        // 启动闪光灯调节器
        ambientLightManager.start(cameraManager);

        // 恢复活动监控器
//		inactivityTimer.onResume();

        source = IntentSource.NONE;
        decodeFormats = null;
        characterSet = null;

        if (isfisrt) {
            initCamera(mSurfaceView.getHolder());

            if (handler != null)

                handler.restartPreviewAndDecode();

        }
    }


    private int getCurrentOrientation() {
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            switch (rotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_90:
                    return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                default:
                    return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            switch (rotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_270:
                    return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                default:
                    return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            }
        }
    }

    private static boolean isZXingURL(String dataString) {
        if (dataString == null) {
            return false;
        }
        for (String url : ZXING_URLS) {
            if (dataString.startsWith(url)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

//    private void onPauseOperation() {
//        if (handler != null) {
//            handler = null;
//        }
//        // historyManager = null; // Keep for onActivityResult
//        if (!hasSurface) {
//            mSurfaceView = (SurfaceView) findViewById(R.id.preview_view);
//            SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
//            surfaceHolder.removeCallback(this);
//        }
//    }


    /**
     * 重置相机
     */
//    public void onResumeOperation() {
//        // historyManager must be initialized here to update the history
//        // preference
//        historyManager = new HistoryManager(this);
//        historyManager.trimHistory();
//
//        // CameraManager must be initialized here, not in onCreate(). This is
//        // necessary because we don't
//        // want to open the camera driver and measure the screen size if we're
//        // going to show the help on
//        // first launch. That led to bugs where the scanning rectangle was the
//        // wrong size and partially
//        // off screen.
//        if (cameraManager != null) {
//            Camera camera = cameraManager.getCamera();
//            if (camera != null) {
//                camera.release();
//            }
//        }
//
//        cameraManager = new CameraManager(getApplication());
//
//        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
//        viewfinderView.setCameraManager(cameraManager);
//
//        resultView = findViewById(R.id.result_view);
//        statusView = (TextView) findViewById(R.id.status_view);
//
//        handler = null;
//        lastResult = null;
//
//        SharedPreferences prefs = PreferenceManager
//                .getDefaultSharedPreferences(this);
//
//
//        resetStatusView();
//
//        beepManager.updatePrefs();
//        ambientLightManager.start(cameraManager);
//
//        inactivityTimer.onResume();
//
//        Intent intent = getIntent();
//
//        copyToClipboard = prefs.getBoolean(
//                PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
//                && (intent == null || intent.getBooleanExtra(
//                Intents.Scan.SAVE_HISTORY, true));
//
//        source = IntentSource.NONE;
//        sourceUrl = null;
//        scanFromWebPageManager = null;
//        decodeFormats = null;
//        characterSet = null;
//
//        if (intent != null) {
//
//            String action = intent.getAction();
//            String dataString = intent.getDataString();
//
//            if (Intents.Scan.ACTION.equals(action)) {
//
//                // Scan the formats the intent requested, and return the result
//                // to the calling activity.
//                source = IntentSource.NATIVE_APP_INTENT;
//                decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
//                decodeHints = DecodeHintManager.parseDecodeHints(intent);
//
//                if (intent.hasExtra(Intents.Scan.WIDTH)
//                        && intent.hasExtra(Intents.Scan.HEIGHT)) {
//                    int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
//                    int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
//                    if (width > 0 && height > 0) {
//                        cameraManager.setManualFramingRect(width, height);
//                    }
//                }
//
//                if (intent.hasExtra(Intents.Scan.CAMERA_ID)) {
//                    int cameraId = intent.getIntExtra(Intents.Scan.CAMERA_ID,
//                            -1);
//                    if (cameraId >= 0) {
//                        cameraManager.setManualCameraId(cameraId);
//                    }
//                }
//
//                String customPromptMessage = intent
//                        .getStringExtra(Intents.Scan.PROMPT_MESSAGE);
//                if (customPromptMessage != null) {
//                    statusView.setText(customPromptMessage);
//                }
//
//            } else if (dataString != null
//                    && dataString.contains("http://www.google")
//                    && dataString.contains("/m/products/scan")) {
//
//                // Scan only products and send the result to mobile Product
//                // Search.
//                source = IntentSource.PRODUCT_SEARCH_LINK;
//                sourceUrl = dataString;
//                decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
//
//            } else if (isZXingURL(dataString)) {
//
//                // Scan formats requested in query string (all formats if none
//                // specified).
//                // If a return URL is specified, send the results there.
//                // Otherwise, handle it ourselves.
//                source = IntentSource.ZXING_LINK;
//                sourceUrl = dataString;
//                Uri inputUri = Uri.parse(dataString);
//                scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
//                decodeFormats = DecodeFormatManager
//                        .parseDecodeFormats(inputUri);
//                // Allow a sub-set of the hints to be specified by the caller.
//                decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
//
//            }
//
//            characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
//
//        }
//
//        mSurfaceView = (SurfaceView) findViewById(R.id.preview_view);
//        mSurfaceView.setDrawingCacheEnabled(true);
//        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
//        if (hasSurface) {
//            // The activity was paused but not stopped, so the surface still
//            // exists. Therefore
//            // surfaceCreated() won't be called, so init the camera here.
//            initCamera(surfaceHolder);
//        } else {
//            // Install the callback and wait for surfaceCreated() to init the
//            // camera.
//            surfaceHolder.addCallback(this);
//        }
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        inactivityTimer.shutdown();
        beepManager.close();

        ambientLightManager.stop();

        // 关闭摄像头
        cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (source == IntentSource.NATIVE_APP_INTENT) {
                    setResult(RESULT_CANCELED);
                    finish();
                    return true;
                }
                if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK)
                        && lastResult != null) {
                    restartPreviewAfterDelay(0L);
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_FOCUS:
            case KeyEvent.KEYCODE_CAMERA:
                // Handle these events so they don't launch the Camera app
                return true;
            // Use volume up/down to turn on light
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                cameraManager.setTorch(false);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                cameraManager.setTorch(true);
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN_GALLERY:
                    handleAlbumPic(intent);

                    break;
            }
        }
    }


    /**
     * 处理选择的图片
     *
     * @param data
     */
    private void handleAlbumPic(Intent data) {


        // 获取返回的图片列表
        List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        // 处理你自己的逻辑
        if (path != null && path.size() > 0) {


            //获取选中图片的路径
            final String photo_path = path.get(0);

            final ProgressDialog mProgress = new ProgressDialog(this);
            mProgress.setMessage("正在扫描...");
            mProgress.setCancelable(false);
            mProgress.show();

            new Thread(new Runnable() {

                @Override
                public void run() {

                    //进行图片识别
                    Result result = QRCodeDecoder.syncDecodeQRCode(BitmapUtils.getDecodeAbleBitmap(photo_path));

                    if (result != null) {
                        Message m = mHandler.obtainMessage();
                        m.what = PARSE_BARCODE_SUC;
                        m.obj = result;
                        mHandler.sendMessage(m);
                    } else {
                        Message m = mHandler.obtainMessage();
                        m.what = PARSE_BARCODE_FAIL;
                        mHandler.sendMessage(m);
                    }

                    mProgress.dismiss();

                }
            }).start();
        }
    }


    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    Bitmap scanBitmap;

//    public Result scanningImage(String path) {
//        if (TextUtils.isEmpty(path)) {
//            return null;
//        }
//        Hashtable<DecodeHintType, String> hints = new Hashtable<>();
//        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码
//
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true; // 先获取原大小
//        scanBitmap = BitmapFactory.decodeFile(path, options);
//        options.inJustDecodeBounds = false; // 获取新的大小
//        int sampleSize = (int) (options.outHeight / (float) 200);
//        if (sampleSize <= 0)
//            sampleSize = 1;
//        options.inSampleSize = sampleSize;
//        scanBitmap = BitmapFactory.decodeFile(path, options);
//        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
//        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
//        QRCodeReader reader = new QRCodeReader();
//        try {
//            return reader.decode(bitmap1, hints);
//        } catch (NotFoundException e) {
//            e.printStackTrace();
//        } catch (ChecksumException e) {
//            e.printStackTrace();
//        } catch (FormatException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


    private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
        // Bitmap isn't used yet -- will be used soon
        if (handler == null) {
            savedResultToShow = result;
        } else {
            if (result != null) {
                savedResultToShow = result;
            }
            if (savedResultToShow != null) {
                Message message = Message.obtain(handler,
                        R.id.decode_succeeded, savedResultToShow);
                handler.sendMessage(message);
            }
            savedResultToShow = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG,
                    "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }


    private void sendReplyMessage(int id, Object arg, long delayMS) {
        if (handler != null) {
            Message message = Message.obtain(handler, id, arg);
            if (delayMS > 0L) {
                handler.sendMessageDelayed(message, delayMS);
            } else {
                handler.sendMessage(message);
            }
        }
    }


    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }

        if (cameraManager.isOpen()) {
            Log.w(TAG,
                    "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        decodeHints, characterSet, cameraManager, true);
            }
            decodeOrStoreSavedBitmap(null, null);
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage(getString(R.string.msg_camera_framework_bug));
        builder.setPositiveButton("OK", new FinishListener(this));
        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }


    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
        lastResult = null;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }


}
